# -*- coding: utf-8 -*-
# @Time : 2021/7/25 10:58
# @Author : zy7y
# @Gitee : https://gitee.com/zy7y
# @File : LoginPage.py
# @Project : SeleniumPOM
"""
登录页面
"""
from typing import Union

from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By

from Pages.BasePage import BasePage
from Config import Config
from Pages.HomePage import HomePage


class LoginPage(BasePage):

    """ 页面 元素 =============== """
    USERNAME = (By.NAME, 'username')
    PASSWORD = (By.NAME, 'password')
    LOGIN_BUTTON = (
        By.CSS_SELECTOR,
        '#login-form > div.submit-row > input[type=submit]')
    ERROR_NOTE = (By.CLASS_NAME, 'errornote')

    """ 页面 初始化 ================== """

    def __init__(self, driver):
        super(LoginPage, self).__init__(driver)
        self.do_visit(Config.BASE_URL)

    """ 页面 行为/动作 ================ """

    def get_login_page_title(self) -> str:
        return self.get_title()

    def is_error_not_enabled(self) -> bool:
        try:
            return self.is_enabled(self.ERROR_NOTE)
        except TimeoutException:
            return False

    def do_login(self, username: str, password: str, other: bool = True) -> Union[HomePage, bool]:
        """
        登录行为
        :param username: 用户名
        :param password: 密码
        :param other: 是否做登录测试
        :return: [HomePage, bool]
        """
        self.do_input(self.USERNAME, username)
        self.do_input(self.PASSWORD, password)
        self.do_click(self.LOGIN_BUTTON)
        return self.is_error_not_enabled() if other else HomePage(self.driver)

